import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { logger } from '../../utils/logger';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES, VALIDATION_ERROR_CODES } from '../../utils/errorCodes';

export class SystemController extends BaseController {
  // 获取系统配置列表
  async getSystemConfigs(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, search = '', type } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {};
      
      if (search) {
        where.OR = [
          { key: { contains: search as string } },
          { description: { contains: search as string } }
        ];
      }

      if (type) {
        where.type = type;
      }

      // 查询系统配置列表
      const [configs, total] = await Promise.all([
        prisma.systemConfig.findMany({
          where,
          select: {
            id: true,
            key: true,
            value: true,
            description: true,
            type: true,
            createdAt: true,
            updatedAt: true
          },
          skip,
          take: limitNum,
          orderBy: { createdAt: 'desc' }
        }),
        prisma.systemConfig.count({ where })
      ]);

      ResponseUtils.paginated(res, configs, total, pageNum, limitNum);
    } catch (error) {
      next(error);
    }
  }

  // 获取系统配置详情
  async getSystemConfigById(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const configId = parseInt(id);

      if (isNaN(configId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的配置ID');
        return;
      }

      const config = await prisma.systemConfig.findUnique({
        where: { id: configId }
      });

      if (!config) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.CONFIG_NOT_FOUND, '系统配置不存在');
        return;
      }

      ResponseUtils.success(res, { config });
    } catch (error) {
      next(error);
    }
  }

  // 根据键获取系统配置
  async getSystemConfigByKey(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { key } = req.params;

      if (!key) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '配置键不能为空');
        return;
      }

      const config = await prisma.systemConfig.findUnique({
        where: { key }
      });

      if (!config) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.CONFIG_NOT_FOUND, '系统配置不存在');
        return;
      }

      ResponseUtils.success(res, { config });
    } catch (error) {
      next(error);
    }
  }

  // 创建系统配置
  async createSystemConfig(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { key, value, description, type = 'STRING' } = req.body;

      if (!key || !value) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '配置键和值不能为空');
        return;
      }

      // 检查配置键是否已存在
      const existingConfig = await prisma.systemConfig.findUnique({
        where: { key }
      });

      if (existingConfig) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.CONFIG_ALREADY_EXISTS, '配置键已存在');
        return;
      }

      const config = await prisma.systemConfig.create({
        data: {
          key,
          value: value.toString(),
          description,
          type
        }
      });

      logger.info(`创建系统配置: ${key}`);
      ResponseUtils.created(res, { config });
    } catch (error) {
      next(error);
    }
  }

  // 更新系统配置
  async updateSystemConfig(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const { key, value, description, type } = req.body;
      const configId = parseInt(id);

      if (isNaN(configId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的配置ID');
        return;
      }

      // 检查配置是否存在
      const existingConfig = await prisma.systemConfig.findUnique({
        where: { id: configId }
      });

      if (!existingConfig) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.CONFIG_NOT_FOUND, '系统配置不存在');
        return;
      }

      // 如果更新键名，检查新键名是否已存在
      if (key && key !== existingConfig.key) {
        const duplicateKey = await prisma.systemConfig.findUnique({
          where: { key }
        });

        if (duplicateKey) {
          ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.CONFIG_ALREADY_EXISTS, '配置键已存在');
          return;
        }
      }

      const updateData: any = {};
      if (key !== undefined) updateData.key = key;
      if (value !== undefined) updateData.value = value.toString();
      if (description !== undefined) updateData.description = description;
      if (type !== undefined) updateData.type = type;

      const config = await prisma.systemConfig.update({
        where: { id: configId },
        data: updateData
      });

      logger.info(`更新系统配置: ${config.key}`);
      ResponseUtils.updated(res, { config });
    } catch (error) {
      next(error);
    }
  }

  // 删除系统配置
  async deleteSystemConfig(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const configId = parseInt(id);

      if (isNaN(configId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的配置ID');
        return;
      }

      // 检查配置是否存在
      const existingConfig = await prisma.systemConfig.findUnique({
        where: { id: configId }
      });

      if (!existingConfig) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.CONFIG_NOT_FOUND, '系统配置不存在');
        return;
      }

      await prisma.systemConfig.delete({
        where: { id: configId }
      });

      logger.info(`删除系统配置: ${existingConfig.key}`);
      ResponseUtils.deleted(res);
    } catch (error) {
      next(error);
    }
  }

  // 批量更新系统配置
  async batchUpdateSystemConfigs(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { configs } = req.body;

      if (!Array.isArray(configs) || configs.length === 0) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '配置列表不能为空');
        return;
      }

      const results = [];
      const errors = [];

      for (const config of configs) {
        try {
          const { key, value, description, type } = config;

          if (!key || !value) {
            errors.push({ key, error: '配置键和值不能为空' });
            continue;
          }

          const updatedConfig = await prisma.systemConfig.upsert({
            where: { key },
            update: {
              value: value.toString(),
              description,
              type
            },
            create: {
              key,
              value: value.toString(),
              description,
              type: type || 'STRING'
            }
          });

          results.push(updatedConfig);
        } catch (error) {
          errors.push({ key: config.key, error: '更新失败' });
        }
      }

      logger.info(`批量更新系统配置: ${results.length} 个成功, ${errors.length} 个失败`);
      ResponseUtils.success(res, { results, errors });
    } catch (error) {
      next(error);
    }
  }







  // 获取系统统计信息
  async getSystemStats(_req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      // 获取用户统计
      const [totalUsers, activeUsers, bannedUsers] = await Promise.all([
        prisma.user.count(),
        prisma.user.count({ where: { status: 'ACTIVE' } }),
        prisma.user.count({ where: { status: 'BANNED' } })
      ]);

      // 获取角色统计
      const [totalRoles, activeRoles] = await Promise.all([
        prisma.role.count(),
        prisma.role.count({ where: { status: 'ACTIVE' } })
      ]);

      // 获取权限统计
      const totalPermissions = await prisma.permission.count();

      // 获取系统配置统计
      const totalConfigs = await prisma.systemConfig.count();

      // 获取操作日志统计
      const [totalLogs, todayLogs] = await Promise.all([
        prisma.operationLog.count(),
        prisma.operationLog.count({
          where: {
            createdAt: {
              gte: new Date(new Date().setHours(0, 0, 0, 0))
            }
          }
        })
      ]);

      // 获取最近7天的操作日志统计
      const last7Days = [];
      for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const startOfDay = new Date(date.setHours(0, 0, 0, 0));
        const endOfDay = new Date(date.setHours(23, 59, 59, 999));

        const count = await prisma.operationLog.count({
          where: {
            createdAt: {
              gte: startOfDay,
              lte: endOfDay
            }
          }
        });

        last7Days.push({
          date: startOfDay.toISOString().split('T')[0],
          count
        });
      }

      // 获取最近30天的用户登录趋势统计（基于lastLoginAt字段）
      const loginTrend = [];
      for (let i = 29; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const startOfDay = new Date(date.setHours(0, 0, 0, 0));
        const endOfDay = new Date(date.setHours(23, 59, 59, 999));

        const loginCount = await prisma.user.count({
          where: {
            lastLoginAt: {
              gte: startOfDay,
              lte: endOfDay
            }
          }
        });

        loginTrend.push({
          date: startOfDay.toISOString().split('T')[0],
          count: loginCount
        });
      }

      // 获取最近12个月的用户登录趋势统计（基于lastLoginAt字段）
      const monthlyLoginTrend = [];
      for (let i = 11; i >= 0; i--) {
        const date = new Date();
        date.setMonth(date.getMonth() - i);
        const startOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
        const endOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999);

        const loginCount = await prisma.user.count({
          where: {
            lastLoginAt: {
              gte: startOfMonth,
              lte: endOfMonth
            }
          }
        });

        monthlyLoginTrend.push({
          month: startOfMonth.toISOString().slice(0, 7), // YYYY-MM 格式
          count: loginCount
        });
      }

      // 获取最近7天的用户活跃度统计（基于updatedAt字段，按小时）
      const hourlyActivity = [];
      const today = new Date();
      const startOfToday = new Date(today.setHours(0, 0, 0, 0));
      
      for (let hour = 0; hour < 24; hour++) {
        const startHour = new Date(startOfToday);
        startHour.setHours(hour, 0, 0, 0);
        const endHour = new Date(startOfToday);
        endHour.setHours(hour, 59, 59, 999);

        const activityCount = await prisma.user.count({
          where: {
            updatedAt: {
              gte: startHour,
              lte: endHour
            }
          }
        });

        hourlyActivity.push({
          hour: hour.toString().padStart(2, '0'),
          count: activityCount
        });
      }

      // 获取最近30天的用户活跃度统计（基于updatedAt字段）
      const userActivityTrend = [];
      for (let i = 29; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const startOfDay = new Date(date.setHours(0, 0, 0, 0));
        const endOfDay = new Date(date.setHours(23, 59, 59, 999));

        const activityCount = await prisma.user.count({
          where: {
            updatedAt: {
              gte: startOfDay,
              lte: endOfDay
            }
          }
        });

        userActivityTrend.push({
          date: startOfDay.toISOString().split('T')[0],
          count: activityCount
        });
      }

      // 获取最近12个月的用户活跃度统计（基于updatedAt字段）
      const monthlyUserActivity = [];
      for (let i = 11; i >= 0; i--) {
        const date = new Date();
        date.setMonth(date.getMonth() - i);
        const startOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
        const endOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999);

        const activityCount = await prisma.user.count({
          where: {
            updatedAt: {
              gte: startOfMonth,
              lte: endOfMonth
            }
          }
        });

        monthlyUserActivity.push({
          month: startOfMonth.toISOString().slice(0, 7), // YYYY-MM 格式
          count: activityCount
        });
      }

      // 获取最活跃的用户
      const topUsers = await prisma.user.findMany({
        select: {
          id: true,
          username: true,
          realName: true,
          _count: {
            select: {
              operationLogs: true
            }
          }
        },
        orderBy: {
          operationLogs: {
            _count: 'desc'
          }
        },
        take: 10
      });

      // 获取最常用的操作
      const topActions = await prisma.operationLog.groupBy({
        by: ['action'],
        _count: {
          action: true
        },
        orderBy: {
          _count: {
            action: 'desc'
          }
        },
        take: 10
      });

      const stats = {
        users: {
          total: totalUsers,
          active: activeUsers,
          banned: bannedUsers
        },
        roles: {
          total: totalRoles,
          active: activeRoles
        },
        permissions: {
          total: totalPermissions
        },
        configs: {
          total: totalConfigs
        },
        logs: {
          total: totalLogs,
          today: todayLogs,
          last7Days
        },
        // 新增登录趋势统计
        loginTrend: {
          daily: loginTrend,
          monthly: monthlyLoginTrend,
          hourly: hourlyActivity
        },
        // 新增用户活跃度统计
        userActivity: {
          daily: userActivityTrend,
          monthly: monthlyUserActivity,
          hourly: hourlyActivity
        },
        topUsers: topUsers.map(user => ({
          id: user.id,
          username: user.username,
          realName: user.realName,
          operationCount: user._count.operationLogs
        })),
        topActions: topActions.map(action => ({
          action: action.action,
          count: action._count.action
        }))
      };

      ResponseUtils.success(res, stats);
    } catch (error) {
      next(error);
    }
  }








}